// 特定题型进度API
import { NextRequest } from 'next/server';
import { ProgressDB } from '@/lib/mysql';
import { getCurrentUser, ApiResponse } from '@/lib/auth';

// 获取特定题型的学习进度
export async function GET(
  request: NextRequest,
  { params }: { params: { topicId: string } }
) {
  try {
    // 验证用户登录
    const currentUser = getCurrentUser();
    if (!currentUser) {
      return ApiResponse.unauthorized('请先登录');
    }

    const { topicId } = params;

    // 获取题型进度
    const progress = await ProgressDB.getTopicProgress(
      currentUser.userId,
      topicId
    );

    if (!progress) {
      return ApiResponse.success({
        topicId,
        totalQuestions: 0,
        correctAnswers: 0,
        totalTime: 0,
        masteryLevel: 0,
        lastPracticedAt: null,
        isLearned: false,
        topicName: null,
      });
    }

    // 将数据库字段(snake_case)转换为前端期望的camelCase
    const mapped = {
      userId: progress.user_id,
      topicId: progress.topic_id,
      topicName: progress.topic_name,
      isLearned: !!progress.is_learned,
      totalQuestions: progress.total_questions || 0,
      correctAnswers: progress.correct_answers || 0,
      totalTime: progress.total_time || 0,
      masteryLevel: progress.mastery_level || 0,
      lastPracticedAt: progress.last_practiced_at || null,
      lastPracticedAtRaw: progress.last_practiced_at,
      updatedAt: progress.updated_at || null,
    };

    return ApiResponse.success(mapped);
  } catch (error) {
    console.error('获取题型进度错误:', error);
    return ApiResponse.serverError('获取题型进度失败');
  }
}
